<template>
  <div v-if="modelValue" class="modal-overlay" @click="handleOverlayClick">
    <div class="apple-card modal-dialog large-dialog" @click.stop>
      <div class="apple-card__header">
        <h2 class="text-heading">编辑用户</h2>
        <button 
          class="close-button apple-button apple-button--text"
          @click="handleClose"
        >
          ✕
        </button>
      </div>

      <form class="apple-card__body" @submit.prevent="handleSubmit">
        <div class="form-sections">
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">用户名</label>
                <input
                  :value="user?.username"
                  class="apple-input disabled-input"
                  disabled
                  readonly
                >
                <div class="form-help">用户名创建后不可修改</div>
              </div>

              <div class="form-group">
                <label class="form-label">真实姓名 *</label>
                <input
                  v-model="form.real_name"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.real_name }"
                  placeholder="请输入真实姓名"
                  maxlength="50"
                  required
                >
                <div v-if="errors.real_name" class="error-message">{{ errors.real_name }}</div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">邮箱地址 *</label>
                <input
                  v-model="form.email"
                  type="email"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.email }"
                  placeholder="请输入邮箱地址"
                  required
                >
                <div v-if="errors.email" class="error-message">{{ errors.email }}</div>
              </div>

              <div class="form-group">
                <label class="form-label">手机号</label>
                <input
                  v-model="form.phone"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.phone }"
                  placeholder="请输入手机号"
                  maxlength="20"
                >
                <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>
              </div>
            </div>
          </div>

          <!-- 组织信息 -->
          <div class="form-section">
            <h3 class="section-title">组织信息</h3>
            
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">员工编号</label>
                <input
                  v-model="form.employee_id"
                  class="apple-input"
                  :class="{ 'apple-input--error': errors.employee_id }"
                  placeholder="请输入员工编号"
                  maxlength="20"
                >
                <div v-if="errors.employee_id" class="error-message">{{ errors.employee_id }}</div>
              </div>

              <div class="form-group">
                <label class="form-label">部门</label>
                <input
                  v-model="form.department"
                  class="apple-input"
                  placeholder="请输入部门"
                  maxlength="50"
                  list="departments"
                >
                <datalist id="departments">
                  <option v-for="dept in departments" :key="dept" :value="dept">
                </datalist>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">职位</label>
                <input
                  v-model="form.position"
                  class="apple-input"
                  placeholder="请输入职位"
                  maxlength="50"
                >
              </div>

              <div class="form-group">
                <label class="form-label">直属领导</label>
                <select v-model="form.manager_id" class="apple-input">
                  <option value="">无直属领导</option>
                  <option 
                    v-for="manager in managers" 
                    :key="manager.id" 
                    :value="manager.id"
                  >
                    {{ manager.real_name }} ({{ manager.username }})
                  </option>
                </select>
              </div>
            </div>
          </div>

          <!-- 状态管理 -->
          <div class="form-section">
            <h3 class="section-title">状态管理</h3>
            
            <div class="form-group">
              <label class="form-label">用户状态</label>
              <select v-model="form.status" class="apple-input">
                <option value="active">激活</option>
                <option value="inactive">未激活</option>
                <option value="suspended">暂停</option>
                <option value="locked">锁定</option>
              </select>
            </div>

            <!-- 系统用户警告 -->
            <div v-if="user?.is_superuser" class="system-user-warning">
              <div class="warning-icon">⚠️</div>
              <div class="warning-content">
                <h4 class="text-body">超级用户</h4>
                <p class="text-caption">此用户为超级用户，某些修改可能受到限制</p>
              </div>
            </div>
          </div>

          <!-- 账户信息 -->
          <div class="form-section">
            <h3 class="section-title">账户信息</h3>
            
            <div class="account-stats">
              <div class="stat-item">
                <div class="stat-label">创建时间</div>
                <div class="stat-value">{{ formatDate(user?.created_at) }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">最后登录</div>
                <div class="stat-value">
                  {{ user?.last_login_at ? formatDate(user.last_login_at) : '从未登录' }}
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-label">登录次数</div>
                <div class="stat-value">{{ user?.login_count || 0 }}</div>
              </div>
            </div>
          </div>
        </div>
      </form>

      <div class="apple-card__footer">
        <button 
          type="button"
          class="apple-button apple-button--secondary"
          @click="handleClose"
        >
          取消
        </button>
        <button 
          type="submit"
          class="apple-button apple-button--primary"
          :disabled="!isFormValid || submitting || !hasChanges"
          @click="handleSubmit"
        >
          {{ submitting ? '保存中...' : '保存更改' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/users'
import { userApi as userDataApi } from '@/api/rbac'
import type { User, UserStatus } from '@/types/rbac'

// Props
interface Props {
  modelValue: boolean
  user: User | null
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'updated'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单数据
const form = ref({
  email: '',
  real_name: '',
  phone: '',
  employee_id: '',
  department: '',
  position: '',
  manager_id: null as number | null,
  status: 'active' as UserStatus
})

// 原始数据（用于检测变化）
const originalData = ref({
  email: '',
  real_name: '',
  phone: '',
  employee_id: '',
  department: '',
  position: '',
  manager_id: null as number | null,
  status: 'active' as UserStatus
})

// 表单验证错误
const errors = ref({
  real_name: '',
  email: '',
  phone: '',
  employee_id: ''
})

// 状态
const submitting = ref(false)
const managers = ref<User[]>([])
const departments = ref<string[]>([])

// 计算属性
const isFormValid = computed(() => {
  return form.value.real_name.trim() && 
         form.value.email.trim() && 
         !Object.values(errors.value).some(error => error)
})

const hasChanges = computed(() => {
  return Object.keys(form.value).some(key => {
    const formValue = form.value[key as keyof typeof form.value]
    const originalValue = originalData.value[key as keyof typeof originalData.value]
    return formValue !== originalValue
  })
})

// 验证函数
const validateRealName = () => {
  const realName = form.value.real_name.trim()
  if (!realName) {
    errors.value.real_name = '真实姓名不能为空'
  } else {
    errors.value.real_name = ''
  }
}

const validateEmail = () => {
  const email = form.value.email.trim()
  if (!email) {
    errors.value.email = '邮箱地址不能为空'
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    errors.value.email = '邮箱格式不正确'
  } else {
    errors.value.email = ''
  }
}

const validatePhone = () => {
  const phone = form.value.phone.trim()
  if (phone && !/^[\d\-\+\s]+$/.test(phone)) {
    errors.value.phone = '手机号格式不正确'
  } else {
    errors.value.phone = ''
  }
}

const validateEmployeeId = () => {
  // 员工编号为可选字段，此处可以添加特定的验证逻辑
  errors.value.employee_id = ''
}

// 初始化表单数据
const initializeForm = () => {
  if (props.user) {
    const data = {
      email: props.user.email,
      real_name: props.user.real_name,
      phone: props.user.phone || '',
      employee_id: props.user.employee_id || '',
      department: props.user.department || '',
      position: props.user.position || '',
      manager_id: props.user.manager_id,
      status: props.user.status as UserStatus
    }
    
    form.value = { ...data }
    originalData.value = { ...data }
    
    // 清除错误
    Object.keys(errors.value).forEach(key => {
      errors.value[key as keyof typeof errors.value] = ''
    })
  }
}

// 加载数据
const loadManagers = async () => {
  try {
    const response = await userDataApi.getUsers({ size: 100, status: 'active' })
    if (response.success) {
      // 排除当前用户，避免将自己设为管理者
      managers.value = response.data.filter(u => u.id !== props.user?.id)
    }
  } catch (error) {
    console.error('加载管理者列表失败:', error)
  }
}

const loadDepartments = async () => {
  try {
    const response = await userDataApi.getUsers({ size: 1000 })
    if (response.success) {
      const deptSet = new Set(response.data.map(u => u.department).filter(Boolean))
      departments.value = Array.from(deptSet).sort()
    }
  } catch (error) {
    console.error('加载部门列表失败:', error)
  }
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

// 点击遮罩关闭
const handleOverlayClick = () => {
  handleClose()
}

// 提交表单
const handleSubmit = async () => {
  if (!props.user) return
  
  // 执行所有验证
  validateRealName()
  validateEmail()
  validatePhone()
  validateEmployeeId()
  
  if (!isFormValid.value || !hasChanges.value) {
    return
  }
  
  submitting.value = true
  
  try {
    const updateData: any = {}
    
    // 只提交变更的字段
    Object.keys(form.value).forEach(key => {
      const formValue = form.value[key as keyof typeof form.value]
      const originalValue = originalData.value[key as keyof typeof originalData.value]
      if (formValue !== originalValue) {
        updateData[key] = formValue || undefined
      }
    })
    
    if (Object.keys(updateData).length === 0) {
      ElMessage.info('没有需要更新的内容')
      return
    }
    
    const response = await userApi.updateUser(props.user.id, updateData)
    
    if (response.success) {
      emit('updated')
      handleClose()
      ElMessage.success('用户更新成功')
    }
  } catch (error: any) {
    console.error('更新用户失败:', error)
    
    // 处理特定错误
    if (error.response?.data?.detail) {
      const detail = error.response.data.detail
      if (detail.includes('邮箱已存在')) {
        errors.value.email = '邮箱已存在'
      } else if (detail.includes('员工编号已存在')) {
        errors.value.employee_id = '员工编号已存在'
      } else {
        ElMessage.error(detail)
      }
    } else {
      ElMessage.error('更新用户失败')
    }
  } finally {
    submitting.value = false
  }
}

// 监听表单变化
watch(() => form.value.real_name, validateRealName)
watch(() => form.value.email, validateEmail)
watch(() => form.value.phone, validatePhone)
watch(() => form.value.employee_id, validateEmployeeId)

// 监听对话框打开和用户变化
watch([() => props.modelValue, () => props.user], ([newValue, newUser]) => {
  if (newValue && newUser) {
    initializeForm()
    loadManagers()
    loadDepartments()
  }
}, { immediate: true })

onMounted(() => {
  if (props.modelValue && props.user) {
    loadManagers()
    loadDepartments()
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.large-dialog {
  width: 100%;
  max-width: 700px;
  max-height: 90vh;
  overflow-y: auto;
  animation: modalSlideIn var(--duration-normal) var(--ease-out);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.apple-card__header {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-button {
  position: absolute;
  right: 0;
  padding: var(--spacing-xs);
  font-size: 18px;
  opacity: 0.6;
}

.close-button:hover {
  opacity: 1;
}

.form-sections {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: var(--spacing-xs);
}

.form-section {
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 1px solid var(--border-secondary);
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--color-primary);
  font-size: 16px;
  font-weight: 600;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-md);
}

.form-group {
  margin-bottom: var(--spacing-md);
}

.form-label {
  display: block;
  margin-bottom: var(--spacing-xs);
  font-weight: 500;
  color: var(--text-primary);
}

.form-help {
  margin-top: var(--spacing-xs);
  font-size: 12px;
  color: var(--text-tertiary);
}

.error-message {
  margin-top: var(--spacing-xs);
  font-size: 12px;
  color: var(--color-danger);
}

.disabled-input {
  background-color: var(--bg-tertiary);
  color: var(--text-tertiary);
  cursor: not-allowed;
}

.system-user-warning {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background-color: rgba(255, 149, 0, 0.1);
  border-left: 4px solid var(--color-warning);
  border-radius: var(--radius-medium);
  margin-bottom: var(--spacing-md);
}

.warning-icon {
  font-size: 20px;
  margin-top: 2px;
}

.warning-content h4 {
  margin: 0 0 var(--spacing-xs) 0;
  color: var(--color-warning);
}

.warning-content p {
  margin: 0;
}

.account-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-medium);
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: var(--text-tertiary);
  margin-bottom: var(--spacing-xs);
}

.stat-value {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.apple-card__footer {
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .modal-overlay {
    padding: var(--spacing-md);
  }
  
  .large-dialog {
    max-height: 95vh;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .account-stats {
    grid-template-columns: 1fr;
  }
  
  .apple-card__footer {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .apple-card__footer .apple-button {
    width: 100%;
  }
}
</style>